// xc_lshop/shop/user/balance/recharge.js
var actmember = require('../../../../xc/model/member')
var order_bill = require('../../model/order_bill')
var app =getApp();

Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],
  /**
   * 页面的初始数据
   */
  data: {
    payway: "1",
    payitem:{
       remark:"",
       givemoney:0,
       givescore:0,
       price:0
    },
    listcur: "-1",
    inputval:"",
    goldcoinname:"金币",
    formdata:{}
  },
  xcloaddata: function (options, config) {
    console.log("config")
    console.log(config)
    var update={};
    if(config.task){
      update['goldcoinname']=config.task.goldcoin;
      update['taskconfig']=config.task;

    }
  
    if(config.payment){
      update['paymentconfig']=config.payment;
      // if(config.payment.rechargeitems)
    }

    if (config.prothem) {
      if (config.prothem.themcolor) {
        update['themconfig']=config.prothem.themcolor.config;
      }
    }

    this.setData(update)
  },
  withdrawal: function () {
    var that = this
    if (this.data.member.memberinfo) {
      var cashoutcom = that.selectComponent("#cashoutcom");
      cashoutcom.showmodel('amount', this.data.member.memberinfo);
    } else {
      wx.showToast({
        title: '等待数据加载',
      })
    }
  },
  afterlogin: function (options, config, userinfo) {
    var that = this;
    that.setData({
      "member": userinfo
    })
    if (userinfo.member_id == 0) { //未登录
      this.login()
    } else{
      that.getpagelist(that, 1, {})

    }
    // else { //已登入
    //   that.getloginconfig(config)
    //   that.updatesimplevipinfo();
    //   acttoolv2.getLocation().then(locres => {
    //     if (config.club.status == 1 && app.globalData.member.memberinfo.groupclubid) {
    //       that.getmycloubinfo();
    //     }
    //   })
    // }
  },
  cashoutrecord(){
    wx.navigateTo({
      url: '/xc_lshop/shop/user/balance/details',
    })
  },
  changeamount(e){
    var that=this
    var aid=e.currentTarget.dataset.aid
    // console.log("this.data.taskconfig");
    // console.log(this.data.taskconfig);
    // return
    var taskconfig=this.data.taskconfig
    if(taskconfig.tipstatus==1){
      wx.showModal({
        title:taskconfig.exchangepopuptitle?taskconfig.exchangepopuptitle:'提示',
        content: taskconfig.exchangepopup?taskconfig.exchangepopup:'确认转化',
        success (res) {
          if (res.confirm) {
            that._changeamount(aid)
          } else if (res.cancel) {
            console.log('用户点击取消')
          }
        }
      })
    }else{
      that._changeamount(aid)
    }
  },
  _changeamount(aid){
    var that=this;
    this.setData({
      amountchanging:true
    })
    actbill.changeamount(aid).then(res => {
      if (res["status"] == 1) {
        that.getpagelist(that, 1)
        wx.showToast({
          title: "操作成功"
        })
      } else {
        wx.showToast({
          title: "操作失败"
        })
      }
      that.setData({
        amountchanging:false
      })
    })
  },
  getpagelist(that, rest, strwhere) {
    if (rest == 1) {
      if (!strwhere) {
        strwhere = {}
      }
      strwhere['auth'] = 'user';
      strwhere['unchangeamount']=1
      // strwhere["status"] = this.data.activetab
      that.setData({
        modellist: [],
        isempty: false
      });
    }
    order_bill.offset(that, rest, strwhere).then(function (result) {
      var updatemdoel = {};
      if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {
        if (result["obj"]["modellist"].length < 1) {
          updatemdoel["isempty"] = true
        } else if (rest == 1) {
          updatemdoel["modellist"] = result["obj"]["modellist"];
        } else {
          if (result["obj"]["modellist"].length > 0) {
            updatemdoel["modellist"] = that.data.modellist.concat(result["obj"]["modellist"]);
          }
        }
      }
      // that.selectComponent("#ordercomment").showmodel( updatemdoel["modellist"][0],"order")      
      // wx.stopPullDownRefresh();
      that.setData(updatemdoel);
    }, function () {

    });
  },
   // 登录注册
  login() {
    var that = this;
    app.xc_sys_config.authop.oppower("login").then(function (res) {
        that.setData({
          "member": app.globalData.member
        })
      })
  },
  //支付方式
  onChange(event) {
    this.setData({
      payway: event.detail,
    });
  },
  //金额
  changemoney(e) {
    if (e.detail.value) {
      var num=e.detail.value * 1;
      var inputval=num.toFixed(2)
      num=parseInt(inputval*100)
    
      this.setData({
        'payitem.price': num,
        'payitem.givemoney': 0,
        'payitem.givescore': 0,
        'payitem.remark': "充值金额："+inputval,
         inputval:inputval,
         listcur: "-1",
      })
    } else {
      var dataset = e.currentTarget.dataset;
    
      var item=dataset.item;
      var payitem={};
      payitem['remark']=item.name +"(赠送金额"+item.givescore+"赠送"+this.data.integralname+"+"+item.givescore+")";
      payitem['givemoney']=(item.givemoney * 1).toFixed(2) * 100;
      payitem['givescore']=item.givescore * 1;
      payitem['price']=(item.price * 1).toFixed(2) * 100;

   
      var index = dataset.index;
      this.setData({
        listcur: index,
        payitem:payitem,
        inputval:""
      })
    }

  },
  //充值
  onClickButton(){
    var that=this;
    var error="";
    if(!that.data.payway){
      error="请选择支付方式"
    }
    if(that.data.payitem.price<=0){
      error="充值金额不能小于等于0"
    }
    // console.log(error)
    if(error){
      wx.showToast({
        icon:'none',
        title: error,
      })
      return;
    }

    var model={};
    model['payway']=that.data.payway;
    model['payitem']=that.data.payitem;
    // console.log(model)
    // return;
    actmember.balacerecharge(model).then(function (restmodel) {
      if (restmodel["status"] == 1) {
        var template_ids = restmodel["template_ids"]
        if (restmodel["paytype"] == 1) {
          var pay_params = restmodel["pay_params"];
          wx.requestPayment({
            timeStamp: pay_params["timeStamp"],
            nonceStr: pay_params["nonceStr"],
            package: pay_params["package"],
            signType: pay_params['signType'],
            paySign: pay_params["paySign"],
            success(res) {
              // if (template_ids&&template_ids.length>0) {
              //   wx.requestSubscribeMessage({
              //     tmplIds: template_ids,
              //     success(res) { }
              //   })
              // }
      

              order_bill.queryorder(restmodel["id"]).then(function (queryreslut) {
          
                if (queryreslut["status"] == 1) {
                  wx.showToast({
                    title: '充值成功',
                  })
                 
                  var all=that.data.member.memberinfo.amount * 1 + model['payitem']['price'] * 1 + model['payitem']['givemoney'] * 1;
                  
                  that.setData({
                    "member.memberinfo.amount": all
                  })
                  app.globalData.member.memberinfo.amount=all
                  app.globalData.member.memberinfo.score=that.data.member.memberinfo.score * 1 + model['payitem']['givescore'] * 1

                  // wx.redirectTo({
                  //   url: '../order/index?opstatus=0',
                  // }) 
                }                
              })
            },
            fail(res) {
              if (res["errMsg"] == "requestPayment:fail cancel") {
                wx.showModal({
                  title: '订单未支付',
                  content: '订单未支付',
                  showCancel:false,
                  success(res) {
                    
                  }
                })
              }

            }
          })
        } else if (restmodel["paytype"] == 2) {
          //余额支付
         if(template_ids &&template_ids.length>0)
         {
          wx.requestSubscribeMessage({
            tmplIds: template_ids,
            success(res) { }
          })
         }
         wx.redirectTo({
          url: '../order/index?opstatus=0',
        }) 

          // wx.showModal({
          //   title: '错误',
          //   content: restmodel["message"],
          // })
        }
      } else {
        wx.showModal({
          title: '错误',
          content: restmodel["message"],
        })
      }
      
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
     
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    if(that.data.taskstatus==1){
      that.getpagelist(that, -1)

    }
  },

  
})